/*global _, DPL, $, iScroll */
/*jslint devel: true, browser: true, undef: true, sloppy: true, regexp: true, plusplus: true,
vars: true, nomen: true, white: true, maxlen: 150, indent: 4 */
////////////////////  lib  ////////////////////
_.ext.ini();
DPL.ini();

////////////////////  biz  ////////////////////
_.action.extend({
	'start': function () {
		//_.dice.start();
	},
	'stop': function () {
		//_.dice.stop();
	},
	'show-history': function () {
		_.card.showHistory();
	},
	'clear-history': function () {
		_.config.del('history');
	}
});

//card
_.card = {
	emptyWord: '(Empty)',
	ini: function () {
		this._getHistory();
		this._getElem();
		//this._iniState();
		this._bind();
		this._iniWords();
	},
	_getElem: function () {
		this.jSection = $('section.card');
		this.jWrapper = this.jSection.find('.cards');
		this.jCards = this.jWrapper.find('li');
		this.jHistoryCounter = this.jSection.find('.info .amount');
	},
	_iniState: function () {
		var _ns = this;
		this.cards = [];
		this.jCards.each(function () {
			var id = this.id;
			_ns.cards[id] = this;
			this.j = this.j || $(this);
			this.j.removeClass('opened').addClass('covered').show();
			this.j.attr('isCovered', '1');
			this.jAmount = this.j.find('.amount');
			this.jWord = this.j.find('b');
			var amount = _.dict[id].length;
			this.jAmount.html(amount);
			//_ns.refreshCat(elem.jCard.attr('id'));
		});
		this.jHistoryCounter.html(this.history.length);
	},
	_bind: function () {
		var _ns = this;
		this.eventName = _.ua.isTouchDevice ? 'touchstart' : 'mousedown';
		this.jWrapper.on(this.eventName, function (e) {
			var elem = e.target;
			if (_.include(['li', 'b', 'i'], elem.tagName.toLowerCase())) {
				_ns.resetCardsExcept(elem);
				_ns.flipCard(elem);
			}
		});
	},
	resetCardsExcept: function (elem) {
		var _ns = this;
		elem.j = elem.j || $(elem);
		elem.jCard = elem.jCard || elem.j.closest('li');
		this.jCards.each(function () {
			this.j = this.j || $(this);
			if (elem.jCard[0] !== this && this.j.attr('isCovered') !== '1') {
				_ns.flipCard(this);
			}
		});
	},
	flipCard: function (elem) {
		elem.j = elem.j || $(elem);
		elem.jCard = elem.j.closest('li');
		if (elem.jCard.attr('isCovered') === '1') {
			this._openCard(elem.jCard);
		} else {
			this._coverCard(elem.jCard);
		}
	},
	_coverCard: function (jCard) {
		jCard.removeClass('opened').addClass('covered');
		jCard.attr('isCovered', '1');
		if (jCard.attr('isEmpty')) {
			jCard.addClass('empty');
			_.log('[Hint] This slot is empty!');
		}
	},
	_openCard: function (jCard) {
		this.refreshCat(jCard.attr('id'));
		jCard.removeClass('covered').addClass('opened');
		jCard.attr('isCovered', '0');
	},
	refreshCat: function (id) {  //called by ._openCard()
		var card = this.cards[id];
		card.j = card.j || $(card);
		var word = this.pickWord(id);
		var amount = _.dict[id].length;
		card.jAmount.html(amount);
		if (!amount) {
			card.jAmount.addClass('error');
			card.j.attr('isEmpty', '1');
		}
		card.jWord.html(word);
	},
	pickWord: function (id) {  //called by .refreshCat()
		var db = _.dict[id];
		var word = '';
		do {
			word = db.shift() || this.emptyWord;
		} while (_.include(this.history, word));
		if (word !== this.emptyWord) {
			this._addHistory(word);
			this._setHistory();
		}
		return word;
	},
	//prepare words
	_iniWords: function () {
		var _ns = this;
		_.task.on('load', function () {
			_ns._filterWords();
			_ns._combineWords();
			_ns._iniState();
		});
	},
	_filterWords: function () {
		var _ns = this;
		_.each(_.dict, function (n, i, a) {  //loop cat
			var t = n;
			_.each(_ns.history, function (n) {  //loop word
				t = _.without(t, n);
			});
			a[i] = _.shuffle(t);
		});
	},
	_combineWords: function () {
		_.dict.all = _.shuffle(_.union(
			_.dict.man,
			_.dict.obj,
			_.dict.act,
			_.dict.adj
		));
	},
	//history fn
	_getHistory: function () {
		this.history = _.str.parseJSON(_.config.get('history') || '[]');
		alert('Found ' + this.history.length + ' word(s) in history!');
	},
	_addHistory: function (s) {
		this.history.unshift(s);
		this.jHistoryCounter.html(this.history.length);
	},
	_setHistory: function () {
		_.config.set('history', JSON.stringify(this.history));
	},
	showHistory: function () {
		var a = this.history || [];
		//var a = _.first(this.history, 20);
		//if (this.history.length > 20) {a.push('...');}
		var r = a.length ? a.join(', ') : '(Empty History)';
		alert(r);
	}
};

//dice
_.dice = {
	ini: function () {
		this.timer = null;
		this.index = 1;
		this.isRolling = false;
		this._getElem();
		this._bind();
	},
	_getElem: function () {
		this.jSection = $('section.dice');
		this.jWrapper = $('div.dice ul');
		this.jBtnWrapper = $('section.dice .act');
	},
	_bind: function () {
		var _ns = this;
		var eventName = _.ua.isTouchDevice ? 'touchstart' : 'mousedown';
		this.jSection.on(eventName, function () {
			if (_ns.isRolling) {
				_ns.stop();
			} else {
				_ns.start();
			}
		});
		if (_.ua.isTouchDevice && navigator.standalone) {
			_.dom.jDoc.on('touchmove', function (e) {
				e.preventDefault();
			});
		}
	},
	_play: function () {
		var _ns = this;
		this.timer = setInterval(function () {
			_ns.index = _ns.index >= 6 ? 1 : _ns.index + 1;
			_ns.jWrapper.attr('class', 'dice' + _ns.index);
		}, 25);
	},
	start: function () {
		this.isRolling = true;
		this._play();
	},
	stop: function () {
		this.isRolling = false;
		clearInterval(this.timer);
	}
};

//debug
_.debug = {
	ini: function () {
		var jWrapper = $('#debug');
		if (!navigator.standalone) {
			_.config.debug = true;
			jWrapper.show();
		}
	}
};



////////////////////  ini  ////////////////////
$(function () {
	_.dice.ini();
	_.card.ini();
	_.debug.ini();
});
